/*
 * Copyright (c) 2021 Talkweb Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <stdio.h>
#include <unistd.h>

#include "ohos_init.h"
#include "cmsis_os2.h"
#include "iot_gpio.h"
#include "iot_gpio_ex.h"
#include "iot_pwm.h"

#define TASK_STACK_SIZE 4*1024
#define TASK_PRIO 25
#define LED_GPIO 9

#define PWM_CHANGE_TIMES 100
#define PWM_FREQ 400000
#define LED_INTERVAL_TIME_US 25000
#define IOT_PWM_PORT_PWM0 0

static void *PwmTask(const char *arg)
{
    (void)arg;

    printf("-----entry PwmTask -----\r\n");

     //初始化LED GPIO
    IoTGpioInit(LED_GPIO);
    //设置LED GPIO为输出模式
    IoTGpioSetDir(LED_GPIO, IOT_GPIO_DIR_OUT);
    //设置输出方式为LED GPIO的功能复用为PWM
    IoSetFunc(LED_GPIO, IOT_IO_FUNC_GPIO_9_PWM0_OUT);
    
    //初始化PWM0设备
    IoTPwmInit(IOT_PWM_PORT_PWM0);


    while (1) {
        for (int duty = PWM_CHANGE_TIMES-1; duty > 0 ; duty--) {
            // output PWM with different duty cycle
            IoTPwmStart(IOT_PWM_PORT_PWM0, duty, PWM_FREQ);
            usleep(LED_INTERVAL_TIME_US);
        }
        for (int duty = 1; duty < PWM_CHANGE_TIMES; duty++) {
            // output PWM with different duty cycle
            IoTPwmStart(IOT_PWM_PORT_PWM0, duty, PWM_FREQ);
            usleep(LED_INTERVAL_TIME_US);
        }
    }
    
    return NULL;
}

static void PwmExample(void)
{
    osThreadAttr_t attr;
    attr.name = "PwmTask";
    attr.attr_bits = 0U;
    attr.cb_mem = NULL;
    attr.cb_size = 0U;
    attr.stack_mem = NULL;
    attr.stack_size = TASK_STACK_SIZE;
    attr.priority = TASK_PRIO;

    if (osThreadNew((osThreadFunc_t)PwmTask, NULL, &attr) == NULL)
    {
        printf("[thinkgo] Falied to create PwmTask!\n");
    }
    return;
}

APP_FEATURE_INIT(PwmExample);
